package com.k.kpp.configfile;

import org.apache.commons.io.FileUtils;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author k
 */
public class YmlFileModifyServiceImpl {


    /**
     *
     * @param map map
     * @param key spring.datasource.name
     * @param value dss
     */
    private static void modifyTargetMap(Map map, String key, Object value){
        String[] pathArr = key.split("\\.");
        Map spring = (Map) map.get(pathArr[0]);
        if(pathArr.length>2){
            for(int i=1;i<pathArr.length-1;i++){
                spring = (Map) spring.get(pathArr[i]);
            }
        }
        spring.put(pathArr[pathArr.length-1],value);
    }

    public static void updateYaml(String pathname,Map<String,Object> keyValues){
        String backPathname = pathname + ".backup";
        File file = new File(pathname);
        File backupFile = new File(backPathname);
        try (InputStream is = new FileInputStream(file)){
            FileUtils.copyFile(file,backupFile);
            System.out.println("备份完成");

            Yaml yaml = new Yaml();
            Map<String,Object> map = yaml.loadAs(is, Map.class);

            for(Map.Entry<String,Object> entry:keyValues.entrySet()){
                modifyTargetMap(map,entry.getKey(),entry.getValue());
            }

            String r = yaml.dumpAsMap(map);
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write(r);
            fileWriter.flush();
            fileWriter.close();
            System.out.println("修改完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String pathname = "C:\\test\\configmodify\\application-dev.yml";
        Map<String,Object> keyValues = new HashMap<>();
        keyValues.put("spring.second.url","jdbc:postgresql://10.45.40.701:5432/dss");
        keyValues.put("spring.third.url","jdbc:postgresql://10.45.40.802:5432/dss");
        updateYaml(pathname,keyValues);
    }

}
